<template>
  <div>
    <div class="card" style="margin-bottom: 10px">
      <el-input placeholder="请输入患者姓名查询" style="width: 200px" v-model="data.name"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="card">
      <div style="margin-bottom: 10px">
        <el-button type="primary" plain @click="handleAdd">新增</el-button>
        <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      </div>
      <el-table :data="data.tableData" strip @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="name" label="患者姓名"></el-table-column>
        <el-table-column prop="gender" label="性别" :formatter="formatGender"></el-table-column>
        <el-table-column prop="dateOfBirth" label="出生日期"  width="120"></el-table-column>
        <el-table-column prop="contactNumber" label="联系电话" width="120"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column prop="medicalCardId" label="医疗卡号"></el-table-column>
        <el-table-column prop="role" label="角色"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column label="患者头像">
          <template #default="scope">
            <el-image :src="scope.row.avatar" style="width: 40px; height: 40px; border-radius: 50%"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            style="margin-top: 5px"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="data.pageNum"
            :page-sizes="[3, 5, 10, 15, 20]"
            :page-size="data.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="新增或修改患者信息" v-model="data.formVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="100px" style="padding-right: 50px" :rules="rules" ref="patientForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="data.form.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" >
          <el-input v-model="data.form.password" placeholder="密码" show-password ></el-input>
        </el-form-item>
        <el-form-item label="患者姓名" prop="name">
          <el-input v-model="data.form.name" placeholder="患者姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="data.form.gender" placeholder="选择性别" style="width: 100%">
            <el-option label="男" value="M"></el-option>
            <el-option label="女" value="F"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="dateOfBirth">
          <el-date-picker type="date"  format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                          v-model="data.form.dateOfBirth" style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactNumber">
          <el-input v-model="data.form.contactNumber" placeholder="联系电话"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="data.form.address" placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item label="医疗卡号" prop="medicalCardId">
          <el-input v-model="data.form.medicalCardId" placeholder="医疗卡号"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload :action="uploadUrl" list-type="picture" :on-success="handleImgSuccess">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessageBox, ElMessage } from 'element-plus'
// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'

// 定义响应式数据
const data = reactive({
  tableData: [],  // 表格数据
  pageNum: 1,     // 当前页码
  pageSize: 10,   // 每页显示数量
  total: 0,       // 总记录数
  name: null,     // 搜索条件
  formVisible: false, // 表单显示状态
  form: {},       // 表单数据
  ids: [],        // 选中数据的ID
})
const patientForm = ref()

// 分页查询
const load = (pageNum = data.pageNum) => {
  data.pageNum = pageNum
  request.get('/Patients/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list
      data.total = res.data?.total
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 新增数据
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
  console.log(data.formVisible)
}

// 编辑数据
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

// 保存数据
const save = () => {
  const url = data.form.id ? '/Patients/update' : '/Patients/add'
  const method = data.form.id ? 'PUT' : 'POST'
  request({
    url,
    method,
    data: data.form,
  }).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('保存成功')
      data.formVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 删除单条数据
const del = (id) => {
  ElMessageBox.confirm('您确定删除吗？', '确认删除', { type: 'warning' }).then(() => {
    request.delete('/Patients/delete/' + id).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {})
}

// 批量删除
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('您确定批量删除这些数据吗？', '确认删除', { type: 'warning' }).then(() => {
    request.delete('/Patients/delete/batch', { data: data.ids }).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {})
}

// 处理选中的行
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id)
}

// 重置筛选条件
const reset = () => {
  data.name = null
  load()
}

// 处理页码变化
const handleCurrentChange = (pageNum) => {
  load(pageNum)
}
const handleSizeChange=(pageSize)=> {
  data.pageSize = pageSize
  load()
}
const  formatGender = (row) =>{
  return row.gender === 'M' ? '男' : '女';
}

// 处理文件上传的钩子
const handleImgSuccess = (res) => {
  data.form.avatar = res.data  // res.data就是文件上传返回的文件路径，获取到路径后赋值表单的属性
}

// 页面初始化加载数据
load()


// 校验规则
const rules = {
  name: [
    { required: true, message: '请输入患者姓名', trigger: 'blur' },
    { min: 2, max: 15, message: '患者姓名长度需在2-15个字符之内', trigger: 'blur' },
  ],
  username: [
    { required: true, message: '请输入患者登录用户名', trigger: 'blur' },
    { min: 2, max: 15, message: '患者患者登录用户名长度需在2-15个字符之内', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入患者登录密码', trigger: 'blur' },
    { min: 3, max: 15, message: '患者登陆密码长度需在3-15个字符之内', trigger: 'blur' },
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  dateOfBirth: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern:/^1[3-9]\d{9}$/ ,message: '手机号格式有误', trigger: 'blur' },
  ]
}

// 提交表单
const submitForm = () => {
  patientForm.value.validate((valid) => {
    if (valid) {
      save()
    } else {
      ElMessage.error('请填写必须的参数！');
      return false;
    }
  });
}

// 失去焦点时手动触发字段校验
const validateField = (field) => {
  patientForm.value.validateField(field);
}

</script>


<style scoped>

</style>